<!--
 * @Author: Mr.Li
 * @Date: 6/9/2025 14:25
 * @Description: index
-->
<template>
  <div class="d-f">
    <div>
      <TreeEditor :isbtnshow="true" @click-node="handleNodeClick" />
    </div>
    <div class="container-template container">
      <TableSearch
        :query="queryData"
        :options="searchOpt"
        :search="handleSearch"
        @refresh="refreshSearch"
      />
      <el-button type="primary" :loading="uploadLoading" @click="handleUpload"
        >模板导入</el-button
      >
      <TableCustom
        :columns="columns"
        :tableData="fileList"
        :total="page.total"
        :currentPage="queryData.pageNum"
        :delFunc="handleDelete"
        :page-change="changePage"
        @refresh="refresh"
        @changePage="changePage"
        :editFunc="handleEdit"
      >
      </TableCustom>
      <BaseDialog
        v-model="showTemDialog"
        title="表单弹窗"
        :before-close="handleBeforeClose"
        @confirm="submitTem"
      >
        <div class="elegant-form-container">
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
            class="elegant-form"
          >
            <el-form-item label="上传模板" prop="ResourceName">
              <div class="custom-file-upload">
                <input
                  type="file"
                  ref="fileInput"
                  accept=".pptx,.xlsx,.pdf,.docx"
                  @change="onFileChange"
                  class="hidden-file-input"
                />
                <div class="file-upload-area" @click="triggerFileInput">
                  <el-icon class="upload-icon"><Upload /></el-icon>
                  <p class="upload-text">点击选择文件或拖拽文件到此处</p>
                  <p class="file-types">支持 .pptx, .xlsx, .pdf, .docx 格式</p>
                </div>
                <div v-if="fileName" class="file-preview">
                  <el-icon class="file-icon"><Document /></el-icon>
                  <span class="file-name">{{ fileName }}</span>
                  <el-button
                    type="danger"
                    text
                    :icon="Close"
                    @click="clearFile"
                    class="clear-btn"
                  ></el-button>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="模板名称" prop="ResourceName">
              <el-input
                v-model="fileName"
                type="text"
                placeholder="请输入模板名称"
                class="elegant-input"
              />
            </el-form-item>
            <el-form-item label="所属项目" prop="ResourceName">
              <el-tree-select
                v-model="fileProjectId"
                :data="treeData"
                :props="defaultProps"
                check-strictly
                :render-after-expand="false"
                placeholder="请选择所属项目"
                class="elegant-tree-select"
              />
            </el-form-item>
          </el-form>
        </div>
      </BaseDialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import axios from "axios";
import { ref, reactive, onMounted, h } from "vue";
import { ElMessage, ElMessageBox, ElInput } from "element-plus";
import TableCustom from "@/components/table-custom.vue";
import IconDocx from "@/assets/icon_docx.svg";
import IconPdf from "@/assets/icon_pdf.svg";
import IconPptx from "@/assets/icon_pptx.svg";
import iconXlsx from "@/assets/icon_xlsx.svg";
import { documentinfopage, documentInfoRemove } from "@/api/office";
import { FormOption, FormOptionList } from "@/types/form-option";
import TableSearch from "@/components/table-search.vue";
import TreeEditor from "@/components/tree/treeEditor.vue";
import * as projectApi from "@/api/project";
import router from "@/router";
import { Upload, Document, Close } from "@element-plus/icons-vue";

export interface TreeNode {
  projectId: string | number;
  projectName: string;
  sort?: number;
  childrens?: TreeNode[];
}

const defaultProps = {
  children: "childrens",
  label: "projectName",
  value: "projectId",
};

let columns = ref([
  { type: "index", label: "序号", width: 55, align: "center" },
  { prop: "documentId", label: "模板ID", showOverflowTooltip: true },
  { prop: "documentName", label: "模板名称", showOverflowTooltip: true },
  { prop: "projectName", label: "所属项目", showOverflowTooltip: true },
  { prop: "createTime", label: "创建时间", showOverflowTooltip: true },
  { prop: "operator", label: "操作", width: 200 },
]);

const form = ref();
const temFile = ref();
let formData = new FormData();
const fileInput = ref();

const rules = reactive({
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
  ],
  age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
  address: [
    {
      required: true,
      message: "请输入地址",
      trigger: "blur",
      resText: "请输入",
    },
  ],
});

const treeData = ref<TreeNode[]>([]);

// 查询相关
const searchOpt = ref<FormOptionList[]>([
  { type: "input", label: "模板名称", prop: "documentName" },
]);
const handleSearch = (e) => {
  changeTable();
};

const showTemDialog = ref(false);

const page = reactive({
  index: 1,
  size: 10,
  total: 0,
});

const fileList = ref([]);
const fileRef = ref();
const fileName = ref();
const fileProjectId = ref("");
const uploadLoading = ref(false);
const iconMap = {
  DOC: IconDocx,
  xlsx: iconXlsx,
  pptx: IconPptx,
  pdf: IconPdf,
};

const queryData = ref({
  pageNum: 1,
  pageSize: 10,
  orderBy: "createTime",
  conditions: [
    {
      column: "documentName",
      type: "like",
      value: "",
    },
    {
      column: "type",
      type: "like",
      value: "1201",
    },
  ],
  asc: false,
});

const changePage = (val: number) => {
  console.log("val", val);

  queryData.value.pageNum = val;
  init();
};

const changeTable = () => {
  console.log("queryData", queryData);
  init();
};

const refresh = () => {
  init();
};

// 获取树数据
const projectInfoTree = async () => {
  const data: any = await projectApi.postProjectInfoTree();
  treeData.value = data;
};
projectInfoTree();

//点击项目
const handleNodeClick = (id) => {
  fileProjectId.value = id;
  queryData.value.conditions[2] = {
    column: "projectId",
    type: "eq",
    value: id,
  };
  init();
};

const refreshSearch = () => {
  queryData.value = {
    pageNum: 1,
    pageSize: 10,
    orderBy: "createTime",
    conditions: [
      {
        column: "documentName",
        type: "like",
        value: "",
      },
      {
        column: "type",
        type: "like",
        value: "1201",
      },
    ],
    asc: false,
  };
  init();
};

const init = async () => {
  const data: any = await documentinfopage(queryData.value);
  fileList.value = data.records;
  page.total = data.total;
};

init();

const handleUpload = () => {
  showTemDialog.value = true;
  // if (fileProjectId.value) {
  //   fileRef.value.click();
  // } else {
  //   ElMessage.error("请选择项目");
  // }
};

const handleEdit = (row) => {
  router.push({
    name: "template-edit",
    query: {
      fileUrl: row.path,
      id: row.documentId,
      mode: "edit",
    },
  });
};

//拖拽
const triggerFileInput = () => {
  fileInput.value.click();
};

const clearFile = () => {
  fileName.value = "";
  fileRef.value.$el.querySelector("input").value = "";
};

const onFileChange = async (e) => {
  try {
    uploadLoading.value = true;
    // const file= e;
    temFile.value = e.target.files[0];
    formData.append("file", e.target.files[0]);
    fileName.value = temFile.value.name.replace(/\.[^/.]+$/, "");
    formData.append("fileName", fileName.value);
  } catch (e) {
    uploadLoading.value = false;
    console.error(e);
  }
};

const handleBeforeClose = () => {};

const submitTem = async () => {
  if (!fileName.value) {
    ElMessage.error("请上传文件");
    return
  }
  if (!fileProjectId.value) {
    ElMessage.error("请选择项目");
    return
  }
  await formData.append("projectId", fileProjectId.value);
  // 这里自行配置上传接口
  const res = await axios({
    url: "http://10.222.125.103:18086/document/import",
    method: "post",
    headers: {
      "Content-Type": "multipart/form-data",
    },
    data: formData,
    timeout: 1000 * 20,
  });
  uploadLoading.value = false;
  fileList.value.push({
    fileUrl: res.data.data,
    fileType: fileName.value,
    projectId: fileProjectId.value,
  });
  init();
  showTemDialog.value = false;
};

// 删除相关
const handleDelete = async (row: any) => {
  await documentInfoRemove([row.documentId]);
  ElMessage.success("删除成功");
  init();
};
</script>

<style scoped lang="scss">
.container-template {
  padding: 20px;
  margin-left: 20px;
  flex: 1;
}

.filename {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .icon {
    width: 30px;
    height: 30px;
    margin-right: 10px;
  }
}

.elegant-form-container {
  padding: 24px;
  background-color: #fff;
  // border-radius: 12px;
  // box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  // max-width: 600px;
  margin: 0 auto;
}

.elegant-form {
  padding: 0 10px;
}

:deep(.elegant-form .el-form-item) {
  margin-bottom: 28px;
}

:deep(.elegant-form .el-form-item__label) {
  font-weight: 500;
  color: #2c3e50;
  padding-right: 20px;
}

.custom-file-upload {
  width: 100%;
}

.hidden-file-input {
  display: none;
}

.file-upload-area {
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  padding: 30px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #fafbfc;
  margin-bottom: 16px;
}

.file-upload-area:hover {
  border-color: #409eff;
  background-color: #f0f7ff;
}

.upload-icon {
  font-size: 40px;
  color: #909399;
  margin-bottom: 12px;
}

.upload-text {
  color: #606266;
  font-size: 16px;
  margin: 0 0 8px 0;
  font-weight: 500;
}

.file-types {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.file-preview {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.file-icon {
  color: #409eff;
  font-size: 20px;
  margin-right: 10px;
}

.file-name {
  flex: 1;
  color: #303133;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.clear-btn {
  padding: 0;
  margin-left: 8px;
}

.elegant-input :deep(.el-input__inner) {
  // border-radius: 6px;
  height: 40px;
  line-height: 40px;
  // border: 1px solid #dcdfe6;
  transition: all 0.3s;
}

.elegant-input :deep(.el-input__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.elegant-tree-select :deep(.el-select__wrapper) {
  border-radius: 6px;
  transition: all 0.3s;
}

.elegant-tree-select :deep(.el-select__wrapper:hover) {
  border-color: #c0c4cc;
}

.elegant-tree-select :deep(.el-select__wrapper.is-focused) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
</style>

<style lang="scss">
.el-message-box__message {
  width: 100%;
}
</style>
